package com.yanwq.sayhi.tool;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 作者：yanweiqiang。
 * 日期：2016/1/28。
 */
public class ImageTool {

    public static void scale(
            File src,
            File des,
            int maxWidth) throws
            IOException {
        BufferedImage image = ImageIO.read(src);
        float ratio = 1f;

        if (image.getWidth() > maxWidth) {
            ratio = (float) maxWidth / image.getWidth();
        }

        scale(src,
                des,
                ratio);
    }

    public static void scale(
            File src,
            File des,
            float ratio) throws
            IOException {
        BufferedImage result;
        if (!src.exists()) {
            throw new FileNotFoundException(src.getAbsolutePath());
        }

        BufferedImage im = ImageIO.read(src);

        int width = im.getWidth();
        int height = im.getHeight();

        int toWidth = (int) (width * ratio);
        int toHeight = (int) (height * ratio);

        result = new BufferedImage(toWidth,
                toHeight,
                BufferedImage.TYPE_INT_RGB);
        result.getGraphics()
                .drawImage(im.getScaledInstance(toWidth,
                        toHeight,
                        java.awt.Image.SCALE_SMOOTH),
                        0,
                        0,
                        null);

        FileOutputStream nImage = new FileOutputStream(des);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(nImage);
        JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(result);
        jep.setQuality(0.98f,
                false);
        encoder.encode(result,
                jep);
        nImage.close();
    }

    public static String getOSSKey(String url) {
        return url.substring(url.lastIndexOf("/") + 1,
                url.length());
    }
}
